package com.wfh.wfhwx.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjUtil;
import com.wfh.wfhwx.common.BaseResponse;
import com.wfh.wfhwx.common.ResultUtils;
import com.wfh.wfhwx.exception.BusinessException;
import com.wfh.wfhwx.exception.ErrorCode;
import com.wfh.wfhwx.exception.ThrowUtils;
import com.wfh.wfhwx.model.entity.User;
import com.wfh.wfhwx.model.enums.WxMaterialTypeEnum;
import com.wfh.wfhwx.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.material.WxMpMaterial;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * @author fenghuanwang
 */
@RestController
@RequestMapping("/wx/materail")
@Tag( name = "微信素材接口")
@Slf4j
public class WxMetarailController {

    private final WxMpService wxMpService = new WxMpServiceImpl();

    /**
     * 允许上传的图片类型
     */
    private static final List<String> ALLOW_IMG_TYPE = Arrays.asList("bmp", "png", "jpeg", "jpg", "gif");

    /**
     * 允许上传的音频类型
     */
    private static final List<String> ALLOW_VOICE_TYPE = Arrays.asList("mp3", "wma", "wav", "amr");

    /**
     * 允许上传的视频类型
     */
    private static final List<String> ALLOW_VIDEO_TYPE = Collections.singletonList("mp4");
    @Resource
    private UserService userService;

    /**
     * 校验文件类型和大小
     * @param multipartFile
     * @param wxMaterialTypeEnum
     */
    public void validFile(MultipartFile multipartFile, WxMaterialTypeEnum wxMaterialTypeEnum){
        String originalFilename = multipartFile.getOriginalFilename();
        long size = multipartFile.getSize();
        String suffix = FileUtil.getSuffix(originalFilename);
        ThrowUtils.throwIf(StringUtils.isBlank(suffix), ErrorCode.PARAMS_ERROR, "文件后缀不能为空");
        suffix = suffix.toLowerCase();
        final  long oneM = 1024 * 1024;
        switch (wxMaterialTypeEnum) {
            case IMAGE -> {
                ThrowUtils.throwIf(!ALLOW_IMG_TYPE.contains(suffix), ErrorCode.PARAMS_ERROR, "文件类型错误");
                ThrowUtils.throwIf(size > oneM * 2, ErrorCode.PARAMS_ERROR, "文件大小不能超过2M");
            }
            case VOICE -> {
                ThrowUtils.throwIf(!ALLOW_VOICE_TYPE.contains(suffix), ErrorCode.PARAMS_ERROR, "文件类型错误");
                ThrowUtils.throwIf(size > oneM * 2, ErrorCode.PARAMS_ERROR, "文件大小不能超过2M");
            }
            case VIDEO -> {
                ThrowUtils.throwIf(!ALLOW_VIDEO_TYPE.contains(suffix), ErrorCode.PARAMS_ERROR, "文件类型错误");
                ThrowUtils.throwIf(size > oneM * 10, ErrorCode.PARAMS_ERROR, "文件大小不能超过10M");
            }
            default -> throw new BusinessException(ErrorCode.PARAMS_ERROR, "不支持该类型的文件");
        }
    }

    /**
     * 上传素材接口
     * @param appId
     * @param multipartFile
     * @param materialType
     * @param request
     * @return
     */
    @PostMapping("/{appId}/upload")
    @Operation(summary = "上传素材（图片、音频、视频）")
    public BaseResponse<Boolean> uoloadMaterial(@PathVariable String appId,
                                                @RequestPart("file") MultipartFile multipartFile,
                                                String materialType,
                                                HttpServletRequest request){
        // 将前端传递过来的素材类型字符串转换为枚举类型
        WxMaterialTypeEnum wxMaterialTypeEnum = WxMaterialTypeEnum.getEnumByValue(materialType);
        ThrowUtils.throwIf(ObjUtil.isEmpty(wxMaterialTypeEnum), ErrorCode.PARAMS_ERROR, "素材类型错误");
        // 校验文件
        validFile(multipartFile, wxMaterialTypeEnum);
        String originalFilename = multipartFile.getOriginalFilename();
        User loginUser = userService.getLoginUser(request);
        // 创建临时文件存储路径
        String filePath = String.format("%s/%s/%s/%s", System.getProperty("user.dir"), loginUser.getId(), UUID.randomUUID(), originalFilename);
        File file = null;
        try {
            // 保存到临时目录
            file = new File(filePath);
            // 创建微信素材对象
            WxMpMaterial wxMpMaterial = new WxMpMaterial();
            wxMpMaterial.setFile(file);
            wxMpMaterial.setName(originalFilename);
            wxMpMaterial.setVideoTitle(originalFilename);
            // 切换到指定的公众号并调用素材上传接口
            wxMpService.switchover(appId);
            wxMpService.getMaterialService().materialFileUpload(materialType, wxMpMaterial);
            return ResultUtils.success(true);
        }catch (Exception e){
            log.error("上传素材失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传素材失败");
        }finally {
            if (file != null) {
                if (file.exists()){
                    file.delete();
                }
            }
        }
    }

}
